﻿var total_number_of_content = 0;
var sourcelang_="";
var targetlang_="";
var sourceMap = {};//原文键值对
var transMap = {};//译文键值对


function walkTheDOM(node, func) {
	func(node);
	node = node.firstChild;
	while (node) {
		walkTheDOM(node, func);
		node = node.nextSibling;
	}
}

walkTheDOM(document.body, function(node) {
	if (node.nodeType === 3) { // Is it a Text node?
		var text = node.data.trim();
		var parent = node.parentNode;
		if (parent.nodeName != "SCRIPT" && parent.nodeName != "NOSCRIPT"
				&& parent.nodeName != "STYLE" && parent.nodeName != 'TEXTAREA' && parent.id != 'yeebox') {
			if (text.length > 0) {
				// console.log(text);
				total_number_of_content += 1;
			}
		}
	}
});

var dict = {
	"1.国家报道数据分布" : "1.Countries Report Data Distribution",
	"2.媒体资讯走势" : "2.Media Information Trend",
	"3.媒体覆盖统计图" : "3.Media Coverage of The Chart",
	"4.多语言对比分析" : "4.Multilingual Comparative Analysis",
	"5.媒体报道数据分布" : "5.Media Reports Data Distribution",
	"6.全球资讯正负面信息比例" : "6.Global Information Proportion of Positive and Negative Information",
	"7.关联关键词" : "7.Fully Associative Keywords",
	"8.观点分析" : "8.Analysis Views",
	"?走出去" : "globalization",
	"部门工作动态" : "works of sectors",
	"中版" : "CPG",
	"党群工作" : "works of the Party Committee",
	"大佳网" : "dajianet",
	"谭跃" : "Tan Yue",
	"刘伯根" : "Liu Bogen",
	"钱理群" : "Qian Liqun",
	"作    者" : "author",
	"出 版 社" : "press",
	"闲花" : "wild flower",
	"李洁非" : "Li Jiefei",
	"七堂课" : "seven courses",
	"潘凯熊" : "Pan Kaixiong",
	"张纪臣" : "Zhang Jichen",
	"重启教育改革" : "Restart an education reform",
	"只计耕耘莫问收" : "the process matters",
	"偷你的心情，写情歌" : "write love songs with your mood",
	"林秋离在京签售《偷你的心情，写情歌》" : "Ling Qiuli autograph <write love songs with your mood> in Beijing",
	"我不想做一只小老鼠" : "I don't want to be a little mouse",
	"唐宋词举要" : "examples of the poetry in tang and song",
	"当代" : "Contemporary",
	"三联生活周刊" : "Sanlian Life Weekly",
	"英语世界" : "The World of English",
	"汉语世界" : "The World of Chinese",
	"艺术沙龙" : "Art Salon",
	"中国出版传媒商报" : "China Publishing & Media Journal",
	"新华书目报" : "Xinhua Booklist",
	"荣宝斋" : "Rongbaozhai",
	"荣宝拍卖" : "Rongbao auction",
	"文史知识" : "Knowledge of Literature and History",
	"月读" : "Monthly Digest",
	"连环画报" : "Picture Stories",
	"读书" : "Reading",
	"建筑与文化" : "Architecture & Culture",
	"音乐研究" : "Music Studies",
	"小百科知识" : "Encyclopedia Knowledge for the Youth",
	"城市周报" : "City Weekend",
	"书品" : "Shupin",
	"中国音乐教育" : "China Music Education",
	"中国美术馆" : "National Art Museum of China Journal",
	"三联竞争力" : "Advantage",
	"谭跃：把我们的品牌做得更响、更强、更优" : "Tan Yue: Let us make our brand louder, stronger, better",
	"人民文学出版社" : "People’s Literature Publishing House",
	"商务印书馆国际有限公司" : "The Commercial Press International Co., Ltd",
	"中国大百科全书出版社" : "Encyclopedia of China Publishing House",
	"中国美术出版总社" : "China Fine Arts Publishing Group",
	"北京银冠电子出版有限公司" : "Beijing Yinguan Electronic Publishing Co., Ltd",
	"人民音乐音像出版社" : "People’s Music Audio-Video Publishing House",
	"中国对外翻译出版公司" : "China Translation & Publishing Corporation",
	"中国图书进出口（集团）总公司" : "China National Publications Import & Export (Group) Corporation",
	"中国出版传媒商报社" : "China Publishing & Media Journal",
	"世界图书出版公司" : "World Publishing Corporation",
	"世界图书出版公司北京公司" : "World Publishing Corporation, Beijing branch",
	"现代出版社" : "Modern Press Co., Ltd",
	"中版集团数字传媒有限公司" : "China Publishing Group Digital Media Co., Ltd",
	"中版数字设备有限公司" : "DEC",
	"天天出版社" : "Daylight Publishing House",
	"商务印书馆电子音像出版中心" : "The Commercial Press Audio-Video Publishing Center",
	"知识出版社" : "Knowledge Publishing House",
	"人民美术出版社" : "People’s Fine Arts Publishing House",
	"人民音乐出版社" : "People’s Music Publishing House",
	"生活?读书?新知三联书店" : "SDX Joint Publishing Company",
	"东方出版中心" : "Orient Publishing Center",
	"现代教育出版社" : "Modern Education Press",
	"中国民主法制出版社" : "China Democracy and Legal System Publishing House",
	"中国科学文化音像出版社有限公司" : "Chinese Scientific and Cultural Audio-Video Publishing Co., Ltd",
	"北京中新联科技股份有限公司" : "Beijing New Technology Co., Ltd",
	"中版教材有限公司" : "CGP Classroom Publications Co., Ltd",
	"中版国际传媒有限公司" : "CPG International Media Co., Ltd",
	"商务印书馆" : "The Commercial Press",
	"中华书局" : "Zhonghua Book Company",
	"中国大百科全书电子音像出版社" : "Encyclopedia of China Audio-Video Publishing House",
	"连环画出版社" : "Comic Book Publisher",
	"华乐出版社" : "Chinese Music Publishing House",
	"三联书店音像电子出版社" : "SDX Joint Audio-Video Publishing Company",
	"新华书店总店" : "Xinhua Bookstore",
	"荣宝斋" : "Rongbaozhai Publishing House",
	"华文出版社" : "Sino-Culture Press",
	"世图音像电子出版社" : " World Audio-Video Publishing Corporation",
	"北京中版联印刷物资有限公司" : "Beijing CPG Printing Materials Co., Ltd",
	"新华联合发行有限公司" : "Xinhua Joint Publishing Co., Ltd",
	"李洁非 上午写当代，下午写明代" : "Li Jiefei Morning write contemporary, afternoon write Ming",
	"只求学术不追闻达" : "Seek for knowledge rather than great succeed",
	"中版好书2014年度榜出炉" : "CPG good book 2014 annual rank delivered",
	"先生，你想要脏书么？" : "Sir, Do you want dirty book?",
	"漫画家吴淼评《图书营销7堂课》" : " the cartoonist Wu Miao comment <seven courses for selling books>",
	"钱理群 为了完善自我的告别" : "Qian Liqun farewell for self-improvement",
	"中版年度好书出炉 新年再推精品佳作" : "CPG annual rank delivered release new good products in new year",
	"长沙马王堆汉墓简帛集成（全七册）" : "Changsha mawangdui silk writing integration (full seven copies)",
	"商务印书馆：" : "The commercial press:",
	"商务印书馆建千家品牌示范店推广“价值阅读”" : "the commercial press model shop built thousands of brand extension \"value to read\"",
	"12月10～12日，中国出版集团公司召开“学习贯彻中央精神 促进集团明年工作”研讨会。会议全面、系统、集中地学习了十八大以来中央有关重要文件，传达、学习了中央经济工作会议精神。谭跃总裁作会议总结，王涛书记作动员讲话，刘伯根、李岩、潘凯雄副总裁，樊希安、孙月沐副总经理分别作学习发言。" : "10-12 December, China publishing group, the company held a \"study and implement the central spirit Promote group work conference next year. For meeting the exhibition, system, 18 large since the central related important files, communicate, study the central economic work conference spirit. He plans summing-up, President, secretary wang tao, a pep talk, Liu Bogen, li yan, vice President of Pan Kaixiong, xi-an fan, sun yue mu, respectively, a deputy general manager for learning to speak.",
	"谭跃出席CCTV财经频道《对话》栏目" : "Tan Yue attend the \"dialogue\" CCTV financial channel",
	"中版好书榜" : "CPG Book Rank",
	"22年前，时任三联书店总经理的董秀玉遇到哈佛燕京学社社长韩南，一个出版人，一个学者，他们希望合作在中国国内出版一套有价值的学术丛书，这便是后来的“三联·哈佛燕京学术丛书”。" : "22 years ago, then the joint publishing company LTD., general manager of Dong Xiuyu harvard harvard-yenching institute President Korea south, a publisher, a scholar, they hope to cooperation in the domestic publishing a valuable academic series, which is then \"sanlian yanjing, a harvard academic books\".",
	"中版文化公司注册成立" : "CPG culture company registered",
	"人民美术出版社教育资源网" : "ARTSCBS.com",
	"中国图书进出口上海公司" : "China National Publications Import & Export Corporation (Shanghai)",
	"中国图书进出口广州公司" : "China National Publications Import & Export Corporation (Guangzhou)",
	"中国图书进出口（集团）大连公司" : "China National Publications Import & Export (Group) Corporation (Dalian)",
	"中国城市网上美术馆" : "City Gallery of China Online",
	"世界图书出版社上海有限公司" : "World Publishing Corporation (Shanghai)",
	"世界图书出版广东公司" : "World Publishing Corporation (Guangdong)",
	"世界图书出版北京公司" : "World Publishing Corporation (Beijing)",
	"世界图书出版西安公司" : "World Publishing Corporation (Xi’an)",
	"三联韬奋书店" : "Sanlian Taofen Bookstore",
	"华彩书苑" : "Huacai Bookstore",
	"商易华" : "Shangyihua",
	"中国现代书店" : "China Modern Bookstore",
	"中国外文书店网店" : "China Foreign Book Online Store",
	"中图电子期刊导航" : "Navor",
	"荣宝斋画院" : "Rongbaozhai Academy",
	"荣宝斋拍卖" : "Rongbaozhai Auction",
	"黄河网上书店" : "Huanghe River Bookshop",
	"全国出版发行信息网" : "CNONIX",
	"百科在线" : "EC Online Publishing Co., Ltd",
	"东方杂志" : "Eastern Miscellany",
	"中版数据??" : "CBIP",
	"大佳网" : "Dajianet",
	"中国图书对外推广网" : "China Book International",
	"韬奋基金会" : "Taofen Foundation",
	"北京国际图书博览会" : "BIBF",
	"外国学术期刊展" : "Academic Journals Exhibition",
	"全国大中专教材网" : "JiaoCaiChina.com",
	"中国新华书店协会" : "China Xinhua Bookstore Association",
	"新华书目报网站" : "Xinhua Booklist Website",
	"世界最新医学信息文摘杂志" : "World Latest Medicine",
	"现代出版社有限公司" : "Modern Press Co., Ltd",
	"荣宝斋在线" : "Rongbaozhai Online",
	"政府网站" : "Government Websites",
	"中国政府网" : "The Central People’s Government of the People’s Republic of China",
	"国务院新闻办" : "The State Council Information Office",
	"国家新闻出版广电总局" : "State Administration of Press, Publication, Radio, Film and Television",
	"国家版权局" : "National Copyright Administration",
	"发改委" : "National Development and Reform Commission",
	"文化部" : "Ministry of Culture",
	"财政部" : "Ministry of Finance",
	"工业和信息化部" : "Ministry of Industry and Information Technology",
	"人力资源和社会保障部" : "Ministry of Human Resources and Social Security",
	"共产党员网" : "The Communist Party Member Website",
	"谭跃出席全国重点经销商战略合作联席会暨第三届经销商大会并致辞" : "Tan Yue attend national key dealer strategy cooperative meeting, the third dealer meeting and give a speech.",
	"樊希安出席2015年全国馆社高层论坛并致辞" : "Fan Xi'an attend the 2015 national pavilion club senior forum and give a speech.",
	"柳斌杰郭义强等领导出席现代教育出版社成立十周年工作座谈会" : "Liu Fujie Guo Yiqiang and other leaders attended the ten anniversary of the founding of the modern education press work symposium.",
	"出版集团" : "Publishing Groups",
	"中国国际出版集团" : "CIPG",
	"中国教育出版传媒集团" : "China Education Publishing & Media Group Ltd",
	"中国科学出版集团" : "China Science Publishing & Media Group Ltd",
	"上海世纪出版集团" : "Shanghai Century Publishing Group",
	"江苏凤凰出版传媒" : "Phoenix Publishing & Media Inc",
	"中南出版传媒" : "China South Publishing & Media Group",
	"时代出版传媒" : "Time Publishing & Media Co., Ltd",
	"长江出版传媒" : "Changjiang Publishing & Media Co., Ltd",
	"新闻媒体" : "News Media",
	"新华网" : "News",
	"中国网" : "China.com.cn",
	"中国日报" : "China Daily",
	"人民网" : "People.cn",
	"环球网" : "huanqiu.com",
	"央视网" : "CCTV.com",
	"中新网" : "CHINANEWS",
	"光明网" : "Gmw",
	"中经网" : "ce.cn",
	"中国新闻出版网" : "chinaxwcb",
	"中国出版网" : "chinapublish",
	"中国图书出版网" : "bkpcn",
	"中国出版传媒网" : "zgcbcm",
	"中版数据网" : "CPG DataNet",
	"海外出版" : "Publishers Abroad",
	"爱思唯尔" : "Elsevier",
	"圣智学习" : "Cengage Learning",
	"贝塔斯曼" : "Bertelsmann",
	"斯普林格" : "Springer",
	"阿歇特" : "hachette",
	"兰登书屋" : "Random House",
	"约翰?威利" : "John Wiley & Sons",
	"麦格罗?希尔" : "McGraw-Hill",
	"西蒙?舒斯特" : "Simon & Schuster",
	"培生" : "Pearson",
	"牛津大学" : "University of Oxford",
	"剑桥大学" : "University of Cambridge",
	"李叔同刘质平书信集" : "Li shutong Liu zhipin letters",
	"书稿以毛泽东少年励志报国到安邦定国的中国革命传奇故事为线索，力图继承古典文学的创作方法并出新。其创作写意大气磅礴，荡气回肠，既承继古典章法，又汲取现代创意，以重大历史事件为主..." : "Manuscript by MAO zedong youth inspirational country, to the Chinese revolution AnBangDingGuo legend for clues, tries hard to inherit classical literature and new creation methods. His freehand brushwork in traditional Chinese painting creation, aka gut-wrenching, both inherit classical art of composition, and derive the modern creative with an emphasis on major historical events...",
	"《闲花》：有闲心，始能赏闲花" : "\"Spare flower\" : a luxury, can enjoy free flowers",
	"1.Countries Report Data Distribution" : "1.国家报道数据分布",
	"2.Media Information Trend" : "2.媒体资讯走势",
	"3.Media Coverage of The Chart" : "3.媒体覆盖统计图",
	"4.Multilingual Comparative Analysis" : "4.多语言对比分析",
	"5.Media Reports Data Distribution" : "5.媒体报道数据分布",
	"6.Global Information Proportion of Positive and Negative Information" : "6.全球资讯正负面信息比例",
	"7.Fully Associative Keywords" : "7.关联关键词",
	"8.Analysis Views" : "8.观点分析",
	"Home" : "首页",
	"Profile" : "档案",
	"Connections" : "人脉",
	"Jobs" : "职位",
	"Interests" : "资讯",
	"Advanced" : "高级搜索",
	"Business Services" : "商务服务",
	"Try Premium for free" : "免费体验高级账户",
	"Send a message" : "发送站内信",
	"Background" : "背景",
	"Contact info" : "联络方式",
	"Post a Job" : "发布职位",
	"Talent Solutions" : "征才解决方案",
	"Sales Solutions" : "销售解决方案",
	"Inbox" : "站内信",
	"Recommendations" : "推荐",
	"Connections" : "联系人",
	"Following" : "关注",
	"Help Center" : "帮助中心",
	"About" : "关于我们",
	"Press" : "媒体",
	"Bolg" : "博客",
	"Careers" : "职位",
	"Small Business" : "小型企业",
	"Mobil" : "客户端",
	"Developers" : "开发者",
	"Upgrade Your Account" : "升级帐户",
	"User Agreement" : "用户协议",
	"Privacy Policy" : "隐私权政策",
	"Community Guidelines" : "社区准则",
	"Cookie Policy" : "Cookie 政策",
	"Copyright Policy" : "版权政策",
	"Send Feedback" : "意见反馈",
	"People Also Viewed" : "访客还查看过",
	"View recent activity" : "查看最新动态",
	"Suggest an update" : "建议更新",
	"Find references" : "查找推荐人",
	"Share profile" : "分享档案",
	"Save to PDF" : "保存到PDF",
	"Block or report" : "屏蔽或举报",
	"Keep in touch" : "保持联络",
	"Add Connections" : "添加联系人",
	"Find Alumni" : "寻找校友",
	"Google Scholar" : "谷歌学术",
	"Save to Contacts" : "保存到通讯录",
	"Addition info" : "其他信息",
	"Remove connection" : "删除联系人",
	"Who's Viewed Your Profile" : "谁看过你的档案",
	"Edit Profile" : "编辑档案",
	"Get introduced" : "获得引荐",
	"Liked" : "已赞",
	"Like" : "赞",
	"Timeline" : "时间轴",
	"Comment" : "评论",
	"Create Page" : "新建页面",
	"facebook" : "脸书",
	"Facebook" : "脸书",
	"Privacy" : "隐私",
	"Terms" : "条款",
	"Edited" : "编辑过",
	"Reply" : "回复",
	"Invite your friends to like this Page" : "邀请好友赞主页",
	"Suggest Edits" : "编辑建议",
	"Like As Your Page..." : "以主页身份赞",
	"Report Page" : "举报主页",
	"Block Page" : "屏蔽主页",
	"Create a Page" : "创建主页",
	"Top Comments" : "热门评论",
	"View more comments" : "查看更多评论",
	"Founded" : "创立",
	"LIKE BY THIS PAGE" : "此主页赞了",
	"Recent" : "最近",
	"TRENDING AMONG FRIENDS" : "好友爱玩的游戏",
	"RECOMMENDED GAMES" : "推荐游戏",
	"Search" : "搜索",
	"Message" : "发消息",
	"PEOPLE" : "人气",
	"like this." : "赞了",
	"APPS" : "应用",
	"Manage Page" : "管理主页",
	"Create Ads" : "创建广告",
	"Advertising on Facebook" : "Fackbook广告",
	"Activity Log" : "活动日志",
	"News Feed Preference " : "动态消息潘浩设置",
	"Settings" : "设置",
	"Log Out" : "登出",
	"Report a Problem" : "报告问题",
	"News Feed" : "动态消息",
	"Top Stores" : "热门动态",
	"Most Recent" : "最新动态",
	"Events" : "活动",
	"Pages Feed" : "主页动态",
	"Like Pages" : "赞主页",
	"Create Ad" : "创建广告",
	"Game Feed" : "游戏动态",
	"Add Photos/Video" : "添加照片/视频",
	"What's on your mind?" : "你在想什么？",
	"Update Status" : "更新状态",
	"INTERESTS" : "兴趣",
	"Pages and Public Figures" : "主页和公众人物",
	"Manage Your Groups" : "管理你的小组",
	"Create Gourp" : "创建小组",
	"Find New Groups" : "发现小组"
};

// 监听dom变化事件
var whatToObserve = {
	childList : true,
	attributes : true,
	subtree : true,
	attributeOldValue : true,
	attributeFilter : ['class', 'style']
};
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver
		|| window.MozMutationObserver;
var mutationObserverSupport = !!MutationObserver;

var mutationObserver = new MutationObserver(function(mutationRecords) {
	$.each(mutationRecords, function(index, mutationRecord) {
		if (mutationRecord.type === 'childList') {
			if (mutationRecord.addedNodes.length > 0) {
				console.log(mutationRecord.addedNodes.length);
				additional_request_iter = 0;
				for(var i = 0 ; i < mutationRecord.addedNodes.length; i++){
					walkTheDOM(mutationRecord.addedNodes[i], function(node) {
						if (node.nodeType === 3) { // Is it a Text
							// node?
							var text = node.data.trim();
							var parentnode = node.parentNode;
							try {
								JSON.parse(text);
							} catch (err) {
								if (text.length > 0 && text.length < 3096) {
									if (parentnode.nodeName != "SCRIPT"
											&& parentnode.nodeName != "NOSCRIPT"
											&& parentnode.nodeName != "STYLE"
											&& parentnode.nodeName != 'TEXTAREA'
											&& parentnode.id!='yeebox') {
										try {
											term_translation = dict[text];
											if (term_translation)
												node.data = term_translation;
											else {
												$.ajax({
													type : "POST",
													url : 'http://translateport.yeekit.com/translate',
													contentType : "application/json",
													crossDomain : true,
													data : {
														"srcl" : sourcelang_,
														"tgtl" : targetlang_,
														"text" : text
													},
													dataType : "jsonp",
													jsonp : "jsoncallback",
													success : function(json) {
														translation = "";
														if (json) {
															var resTranslation = json.translation[0];
															for (var i = 0; i < resTranslation.translated.length; i++) {
																if (targetlang=='zh'){
																	translation += resTranslation.translated[i].text.replace(/[ ]/g,"");
																}
																else{
																	translation += resTranslation.translated[i].text;
																}
															}
														}
														node.data = translation;
														additional_request_iter += 1;
													}
												});
											}
										} catch (err) {
											console.log("dom change translate error:"+err.message);
										}
									}
								}
							}
						}
					});
					console.info('addtional translation request time in the DOM: '
							+ mutationRecord.addedNodes.length);
				}
			}
		}
	});
});

function transBtnClick(sourcelang, targetlang) {
	sourcelang_=sourcelang;
	targetlang_=targetlang;
	console.info('You clicked the souce is ' + sourcelang
			+ ' and the target is ' + targetlang);
	console.log('total_number_of_content:\t' + total_number_of_content);
	percentage = 0;
	request_iter = 0;
	if (sourcelang == targetlang) {
		progressBar(1.0);
	} else {
		walkTheDOM(document.body, function(node) {
			if (node.nodeType === 3) { // Is it a Text node?
				var text = node.data.trim();
				var parent = node.parentNode;
				if (parent.nodeName != "SCRIPT"
						&& parent.nodeName != "NOSCRIPT"
						&& parent.nodeName != "STYLE"
						&& parent.nodeName != 'TEXTAREA'
						&& parent.id !='yeebox') {
					if (text.length > 0) {
						try {
							JSON.parse(text);
							request_iter += 1;
						} catch (err) {
							try {
								term_translation = dict[text];
								if (term_translation) {
									node.data = term_translation;
									
									sourceMap[term_translation]=text;//存储  “key:译文-->value:原文” 键值对
									transMap[text]=term_translation;//存储 “key:原文-->value:译文” 键值对
									
									request_iter += 1;
								} else {
									$.ajax({
										type : "POST",
										url : 'http://translateport.yeekit.com/translate',
										contentType : "application/json",
										crossDomain : true,
										data : {
											"srcl" : sourcelang_,
											"tgtl" : targetlang_,
											"text" : text
										},
										dataType : "jsonp",
										jsonp : "jsoncallback",
										success : function(json) {
											translation = "";
											if (json) {
												var resTranslation = json.translation[0];
												for (var i = 0; i < resTranslation.translated.length; i++) {
													if (targetlang=='zh'){
														translation += resTranslation.translated[i].text.replace(/[ ]/g,"");
													}
													else{
														translation += resTranslation.translated[i].text;
													}
												}
											}
											node.data = translation;
											
											sourceMap[translation]=text;//存储  “key:译文-->value:原文” 键值对
											transMap[text]=translation;//存储 “key:原文-->value:译文” 键值对
											
											request_iter += 1;
											progress = request_iter
													/ total_number_of_content;
											currentpercentage = progress * 100;
											console.log('current step:'
													+ request_iter
													+ '\t amount:'
													+ total_number_of_content
													+ 'progress:' + progress);
											if (currentpercentage - percentage >= 1) {
												progressBar(percentage / 100);
												percentage = currentpercentage
														- currentpercentage % 1;
											}
											if (progress == 1.0){
												progressBar(progress);
												//发送“查看原文”消息
												var frm = document.getElementById("yeetool");
												frm.contentWindow.postMessage({
													action : "20"
												}, "*");
											}
										},
										error : function(XMLHttpRequest, textStatus, errorThrown){
											console.log('request error, response details textStatus : '+textStatus+',errorThrown : '+errorThrown);
											//发送“请求出错”消息
											var frm = document.getElementById("yeetool");
											frm.contentWindow.postMessage({
												action : "99"
											}, "*");
										}
									});

								}
							} catch (err) {
								request_iter += 1;
								console.log("click translate error:"+err.message);
							}
						}
					}
				}
			}
		});
		console.info('total translation request time in the DOM: '
				+ request_iter);

	}

	if (mutationObserverSupport) {
		mutationObserver.observe(document.body, whatToObserve);
	}
};

// iframe消息互发
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function(e) {
			if (e.data.action == "01") {
				transBtnClick(e.data.sourceLang, e.data.targetLang);
			}else if(e.data.action=="10"){
				getSourceLang();
			}else if(e.data.action=="21"){
				// 查看原文
				lookSource();
			}else if(e.data.action=="31"){
				// 查看译文
				lookTrans();
			}else if(e.data.action=="1002"){
				// 暂不翻译，移除
				removePlugin();
			}
		}, false);

// 更新进度条
function progressBar(index) {
	var frm = document.getElementById("yeetool");
	frm.contentWindow.postMessage({
				action : "51",
				index : index
			}, "*");
}
//获取源语言
function getSourceLang(){
	var htmlNode = document.getElementsByTagName("html")[0];
	var titleNode = document.title;
	var sourceLang = "";
	if(htmlNode.lang != ""){
		sourceLang = htmlNode.lang;
		var frm = document.getElementById("yeetool");
		frm.contentWindow.postMessage({
			action : "11",
			sourceLang : sourceLang
		}, "*");
	}else{
		$.ajax({
			type : "POST",
			url : 'http://54.64.40.131:9006/detection',
			contentType : "application/json",
			crossDomain: true,
			data : {
				text : titleNode
			},
			dataType : "jsonp",
			jsonp : "jsoncallback",
			success : function(json) {
				if(json.errorCode==0){
					sourceLang = json.result;
				}
				var frm = document.getElementById("yeetool");
				frm.contentWindow.postMessage({
					action : "11",
					sourceLang : sourceLang
				}, "*");
			}
		});
	}
}
//查看原文
function lookSource(){
	walkTheDOM(document.body, function(node) {
		if (node.nodeType === 3) {
			var text = node.data.trim();
			var parent = node.parentNode;
			if (parent.nodeName != "SCRIPT"
					&& parent.nodeName != "NOSCRIPT"
					&& parent.nodeName != "STYLE"
					&& parent.nodeName != 'TEXTAREA') {
				if (text.length > 0) {
					try {
						JSON.parse(text);
					} catch (err) {
						term_translation = sourceMap[text];
						if (term_translation) {
							node.data = term_translation;
						}
					}
				}
			}
		}
	});
	//发送“查看译文”消息
	var frm = document.getElementById("yeetool");
	frm.contentWindow.postMessage({
		action : "30"
	}, "*");
}
//查看译文
function lookTrans(){
	walkTheDOM(document.body, function(node) {
		if (node.nodeType === 3) {
			var text = node.data.trim();
			var parent = node.parentNode;
			if (parent.nodeName != "SCRIPT"
					&& parent.nodeName != "NOSCRIPT"
					&& parent.nodeName != "STYLE"
					&& parent.nodeName != 'TEXTAREA') {
				if (text.length > 0) {
					try {
						JSON.parse(text);
					} catch (err) {
						term_translation = transMap[text];
						if (term_translation) {
							node.data = term_translation;
						}
					}
				}
			}
		}
	});
	//发送“查看原文”消息
	var frm = document.getElementById("yeetool");
	frm.contentWindow.postMessage({
		action : "20"
	}, "*");
}

function removePlugin(){
	document.body.style.marginTop = 0;
	document.body.style.position = '';

	var createIframeJs2 = document.getElementById('createIframeJs');
	if (createIframeJs2 != null) {
		createIframeJs2.parentNode.removeChild(createIframeJs2);
	}

	var jqueryJs2 = document.getElementById('jqueryJs');
	if (jqueryJs2 != null) {
		jqueryJs2.parentNode.removeChild(jqueryJs2);
	}

	var iframeJs2 = document.getElementById('iframeJs');
	if (iframeJs2 != null) {
		iframeJs2.parentNode.removeChild(iframeJs2);
	}

	var yeetool = document.getElementById('yeetool');
	if (yeetool != null) {
		yeetool.parentNode.removeChild(yeetool);
	}
}
